package com.tianji.learning.listener;

import cn.hutool.core.collection.CollUtil;
import com.tianji.api.client.course.CourseClient;
import com.tianji.api.dto.course.CourseSimpleInfoDTO;
import com.tianji.api.dto.trade.OrderBasicDTO;
import com.tianji.common.constants.MqConstants;
import com.tianji.learning.domain.po.LearningLesson;
import com.tianji.learning.enums.LessonStatus;
import com.tianji.learning.enums.PlanStatus;
import com.tianji.learning.service.ILearningLessonService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.ExchangeTypes;
import org.springframework.amqp.rabbit.annotation.Exchange;
import org.springframework.amqp.rabbit.annotation.Queue;
import org.springframework.amqp.rabbit.annotation.QueueBinding;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
import java.util.Optional;

@Slf4j
@Component
public class PaySuccessListener {

    @Autowired
    private CourseClient client;

    @Autowired
    private ILearningLessonService lessonService;

    /**
     * 支付完成以后，把课程信息添加到课表
     * */
    @RabbitListener(bindings = @QueueBinding(
            value=@Queue(name = MqConstants.Queue.LEARNING_LESSON_PAY_QUEUE),
            exchange = @Exchange(name = MqConstants.Exchange.ORDER_EXCHANGE, type = ExchangeTypes.TOPIC),
            key = MqConstants.Key.ORDER_PAY_KEY
    ))
    public void onPaySuccess(OrderBasicDTO dto){
        // courseClient根据courseIds查询course信息
        List<CourseSimpleInfoDTO> simpleInfoList = client.getSimpleInfoList(dto.getCourseIds());
        if(CollUtil.isEmpty(simpleInfoList)){
            log.error("根据课程ids查询不到课程信息：{}",dto.getCourseIds());
            return;
        }
        // 填充过期时间
        // 把dto -> po列表
        List<LearningLesson> lessonList = new ArrayList<>();
        for (Long courseId : dto.getCourseIds()) {
            LearningLesson lesson = new LearningLesson();
            lesson.setUserId(dto.getUserId());
            lesson.setCourseId(courseId);
            lesson.setStatus(LessonStatus.NOT_BEGIN.getValue());
            lesson.setPlanStatus(PlanStatus.NO_PLAN.getValue());
            lesson.setLearnedSections(0);
            lesson.setCreateTime(LocalDateTime.now());
            lesson.setUpdateTime(LocalDateTime.now());
            CourseSimpleInfoDTO courseDto = getCourseById(simpleInfoList, courseId);
            if(courseDto == null){
                log.error("根据课程id查询不到课程信息：{}",courseId);
                return;
            }
            if(courseDto.getValidDuration() != null){
                lesson.setExpireTime(LocalDateTime.now().plusMonths(courseDto.getValidDuration()));
            }
            lessonList.add(lesson);
        }
        // 批量插入
        lessonService.saveBatch(lessonList);
    }

    private CourseSimpleInfoDTO getCourseById(List<CourseSimpleInfoDTO> simpleInfoList, Long courseId) {
        Optional<CourseSimpleInfoDTO> any = simpleInfoList.stream().filter(c -> Objects.equals(c.getId(), courseId)).findAny();
        if(any.isPresent()){
            return any.get();
        }
        return null;
    }

}
